#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :api_01.py
# @Time      :2024/11/8 19:17
# @Author    :zhou_yi

from fastapi import APIRouter, Form
from models.BaseModels import CompanyBaseModel
from service.fn_db import companyDB

a01 = APIRouter()


# 名称查询公司
@a01.get('/company/{name}')
async def fetch_company_by_name(name: str) -> CompanyBaseModel:
    _res: dict = await companyDB.fetch_by_name(name)
    company = CompanyBaseModel(**_res)
    return company


# 根据相关性查询公司
@a01.get('/companies')
async def fetch_company_by_relation(r1: str, r2: str = '') -> list[CompanyBaseModel]:
    _res = await companyDB.fetch__by_relation(r1, r2)
    companies = [CompanyBaseModel(**itm) for itm in _res]
    return companies


# 集合中最大的id 与新id
@a01.get('/company_max_and_new_id')
async def company_max_and_new_id() -> list[str]:
    _tuple = await companyDB.max_id_and_new_id()
    return list(_tuple)


# 插入一条公司记录
@a01.post('/company')
async def insert_one_company(company: CompanyBaseModel = Form(...)):
    res: bool = await companyDB.insert_one(company.dict())
    return res


# 修改一条公司记录
@a01.put('/company/{name}')
async def update_one_company(name: str, data: dict):
    await companyDB.update_one({'name': name}, data)
    return True


# 删除一条公司记录
@a01.delete('/company/{name}')
async def delete_one_company(name: str):
    await companyDB.delete_one({'name': name})
    return True


# 插入多条公司记录
@a01.post('/companies')
async def insert_many_company(companies: list[CompanyBaseModel]):
    companies = [itm.dict() for itm in companies]
    res: bool = await companyDB.insert_many(companies)
    return res


if __name__ == '__main__':
    ...
